package com.andy.eqm.server.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.andy.eqm.server.dao.DaoUtils;
import com.andy.eqm.server.dao.DbBatch;
import com.andy.eqm.server.entity.BaseEntity;
import com.andy.eqm.server.entity.UsrGameInfo;
import com.andy.eqm.server.entity.UsrGameLog;
import com.andy.eqm.server.game.GameUser;
import com.andy.eqm.server.game.Global;
import com.andy.eqm.server.socket.MySocketSession;

public class CommonUtils {

	private static Logger logger = LoggerFactory.getLogger(CommonUtils.class);
	
	/**
	 * 离开游戏
	 * @param user
	 * @param action 
	 */
	public static void outRoom(GameUser user, int action) {
		if(user == null)return;
		
		saveDb(user.getUser(),user.getGameInfo());
		
	}
	

	/**
	 * 异步批量操作
	 * @param entity
	 */
	public static void saveDb(BaseEntity... entity){
		try {
			for(BaseEntity en:entity){
				if(en.getId() != null){
					if(en instanceof UsrGameInfo){
						DbBatch.upUsrUser((UsrGameInfo) en);
					}else{
						DaoUtils.update(en);
					}
				}else{
					if(en instanceof UsrGameLog){
						DbBatch.svGameLog((UsrGameLog) en);
					}else{
						DaoUtils.insert(en);
					}
				}
			}
		} catch (Exception e) {
			logger.error("持久化异常",e);
		}
	}

	/**
	 * 后台管理调用增加金币
	 * @param id
	 * @param addCoin
	 */
	public static void addCoin(Long id, Integer addCoin) {
		MySocketSession session = Global.getSession(id);
		if(session != null){
			session.getUser().getGameInfo().addCoin(addCoin);
//			SendUtil.send114(session,session.getUser());
		}else{
			UsrGameInfo gameInfo = DaoUtils.get(id, UsrGameInfo.class);
			gameInfo.addCoin(addCoin);
			saveDb(gameInfo);
		}
	}


}
